package yehang.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import yehang.utils.RespBean;


import javax.servlet.http.HttpServletRequest;


@ControllerAdvice(annotations = {Controller.class, RestController.class})
@Slf4j
public class GlobalResponseHandler {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 方式一：统一返回一个错误的json格式的数据
     *
     * @param request
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public RespBean<String> errorHandlerByJson(HttpServletRequest request, RuntimeException e) throws Exception {
        log.error(e.getMessage(),e);
        return RespBean.error(e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public RespBean<String> ValidError(HttpServletRequest request, MethodArgumentNotValidException e) throws Exception {
        log.error(e.getMessage(),e);
        return RespBean.error(e.getBindingResult().getFieldError().getDefaultMessage());
    }

}